package yf.mall.controller.api;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import com.yf.response.RRException;
import com.yf.service.WxPayService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import yf.mall.common.Const;
import yf.mall.dao.ShopDao;
import yf.mall.entity.*;
import yf.mall.service.*;
import yf.mall.vo.MallOrderVo;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class ApiOrderController {


    @Autowired
    private AddressService addressService;

    @Autowired
    private MallOrderService mallOrderService;

    @Autowired
    private OrderItemService itemService;

    //获取所有地址
    @GetMapping("/address")
    public R addressList(@LoginUserId Long userId) {
        List<AddressEntity> addressEntities = addressService.findByUserId(userId);
        return R.ok(addressEntities);
    }

    @GetMapping("/address/info")
    public R getAddress(@LoginUserId Long userId, Long id) {
        AddressEntity addressEntity = addressService.get(id);
        if (addressEntity == null || !addressEntity.getUserId().equals(userId)) {
            throw new RRException("地址异常!");
        }
        return R.ok(addressEntity);
    }

    //更新地址
    @PostMapping("/address")
    public R addressMerge(@LoginUserId Long userId, AddressEntity addressEntity) {
        if (addressEntity.getUserId() != null) {//用户ID存在判断是否是自己的
            if (!addressEntity.getUserId().equals(userId)) {
                throw new RRException("地址异常!");
            }
        } else {
            addressEntity.setUserId(userId);
        }
        addressEntity = addressService.merge(addressEntity);
        return R.ok(addressEntity);
    }

    //删除地址
    @RequestMapping("/address/remove")
    public R addressRemove(@LoginUserId Long userId, Long id) {
        AddressEntity addressEntity = addressService.get(id);
        if (addressEntity == null || !addressEntity.getUserId().equals(userId)) {
            throw new RRException("地址异常!");
        }
        addressService.delete(id);
        return R.ok();
    }


    @Autowired
    private UserService userService;

    //购物车提交订单
    @RequestMapping("/cart/commit")
    public R commitByCart(@LoginUserId Long userId,Long vipUserId, AddressEntity addressEntity, String remark, Integer payWay, Integer orderType,Integer temp, HttpServletRequest request ,Long recordId) {
        System.out.println(userId);
        userService.validateUser(userId);
        String noticeUrl = ServletUriComponentsBuilder.fromContextPath(request).path(Const.WX_ORDER_PAY_URL).toUriString();
        String payConfig = mallOrderService.commitOrder(userId,vipUserId, addressEntity, remark, payWay, orderType, noticeUrl,temp,recordId);
        return R.ok(payConfig);
    }

    /**
     * 统一下单 请求支付
     *
     * @param orderNo
     * @return
     */
    @RequestMapping("/wx/union")
    public R wxUnion(String orderNo, HttpServletRequest request) {
        MallOrderEntity mallOrderEntity = mallOrderService.findByOrderNo(orderNo);
        if(new Date().getTime()-mallOrderEntity.getOrderTime().getTime()>1000*30*60){
            throw new RRException("订单已经超时,请取消重新下单");
        }
        if (mallOrderEntity == null) {
            throw new RRException("订单不存在!");
        }
        String noticeUrl = ServletUriComponentsBuilder.fromContextPath(request).path(Const.WX_ORDER_PAY_URL).toUriString();
        String payConfig = mallOrderService.unionOrder(mallOrderEntity, noticeUrl);
        return R.ok(payConfig);
    }

    @Autowired
    private WxPayService wxPayService;

    /**
     * 微信支付成功后回调通知
     *
     * @param body
     * @return
     */
    @RequestMapping("/wx/pay")
    @IgnoreAuth
    public String wxPay(@RequestBody String body) {
        Map<String, String> map = wxPayService.handleWxNotice(body);
        String orderNo = map.get("out_trade_no");
        mallOrderService.payByWx(orderNo);
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

//    立即购买
//    @RequestMapping("/detail/commit")
//    public R commitByDetail(@LoginUserId Long userId, Long goodsId, String skuName, Integer quantity, AddressEntity addressEntity) {
//        mallOrderService.commitOrder(userId, goodsId, skuName, quantity, addressEntity);
//        return R.ok();
//    }

    //订单列表
    @RequestMapping("/list")
    public R orderList(@LoginUserId Long userId, int page, int limit,Integer orderType,Integer busType) {
        System.out.println(userId);
        List<MallOrderVo> mallOrderEntities = mallOrderService.listOrder(userId, page, limit,orderType,busType);
        return R.ok(mallOrderEntities);
    }

    @Autowired
    private ShopService shopService;
    //订单详情 TODO 推荐人也可以
    @RequestMapping("/info")
    public R getOrder(@LoginUserId Long userId, Long id, String orderNo,Integer type) {
        MallOrderVo orderVo;

        if (orderNo != null && orderNo.contains(Const.ORDER_NO)){
            orderNo = orderNo.split(Const.ORDER_NO)[1];
        }

        if (id == null) {
            orderVo = mallOrderService.getVo(orderNo);
        } else {
            orderVo = mallOrderService.getVo(id);
        }

        UserEntity userEntity = orderVo.getUser();
        if (orderVo.getUser().getId().equals(Const.ADMIN_ID)) {
            userEntity = orderVo.getFromUser();
        }

        if (!userEntity.getPid().equals(userId) && !userEntity.getId().equals(userId) && !orderVo.getFromUser().getId().equals(userId) && type == null) {
            throw new RRException("订单数据有误!");
        }
        //获取明细
        List<OrderItemEntity> itemEntities = itemService.findByOrderId(orderVo.getMallOrder().getId());
        orderVo.getMallOrder().setItems(itemEntities);
        //获取店铺
        ShopEntity shopEntity= null;
        if (orderVo.getMallOrder().getShopId() != null){
            shopEntity  = shopService.findByUserId(orderVo.getMallOrder().getShopId());
        }else {
            shopEntity  = shopService.findByUserId(orderVo.getMallOrder().getFromUserId());
        }
        if (shopEntity !=null){
            orderVo.setShopEntity(shopEntity);
        }
        return R.ok(orderVo);
    }

    /**
     * 撤销订单 发货订单才能撤销
     *
     * @param userId
     * @param orderId
     * @return
     */
    @RequestMapping("/remove")
    public R deleteOrder(@LoginUserId Long userId, Long orderId) {
        mallOrderService.deleteOrder(userId, orderId);
        return R.ok();
    }

    /**
     * 下载用户支付了的订单
     *
     * @param response
     * @param code
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("/download/paid")
    @IgnoreAuth
    public R downLoadPaid(HttpServletResponse response, String code, String startDate, String endDate) {
        mallOrderService.downLoad(response, code, startDate, endDate);
        return R.ok();
    }

    @Autowired
    private AccountService accountService;

    /**
     * @param userId
     * @param orderNo
     * @return
     */
    @RequestMapping("/sureReceipt")
    public R sureReceipt(@LoginUserId Long userId, @RequestParam("orderNo") String orderNo) {
        this.mallOrderService.sureReceipt(userId, orderNo);
        return R.ok();
    }

    /**
     * Long
     * 根据用户id去查询该用户的订单状态
     *
     * @param userId
     * @param status
     * @return
     */
    @RequestMapping("findOrdersByStatus")
    public R findOrdersByStatus(@LoginUserId Long userId, @RequestParam(name = "status", defaultValue = "-1") int status) {
        List<MallOrderVo> mallOrderVos = this.mallOrderService.findByUserIdAndStatus(userId, status);
        return R.ok(mallOrderVos);
    }
}
